package com.zhihesj.anan.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhihesj.anan.system.vo.LoginVo;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


/**
 * @author anan.
 * @version 1.0
 * @create 2020-04-21 15-53
 */
public class JwtUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
          if(request.getContentType().toUpperCase().equals(MediaType.APPLICATION_JSON_UTF8_VALUE.toUpperCase())
                  ||request.getContentType().toUpperCase().equals(MediaType.APPLICATION_JSON_VALUE.toUpperCase())){
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;

            try (InputStream is = request.getInputStream()){
                LoginVo loginVo = mapper.readValue(is, LoginVo.class);
                authRequest = new UsernamePasswordAuthenticationToken(loginVo.getUsername(),loginVo.getPassword());
            }catch (IOException e) {
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken("", "");
            }finally {
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            }
        }
        else {
            return super.attemptAuthentication(request, response);
        }
    }
}
